package com.smsc.headend.connector.service.impl;

import cn.hutool.core.date.SystemClock;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.smsc.headend.connector.service.DeviceStatusService;
import com.smsc.headend.connector.service.FeignAssetManagementService;
import com.smsc.headend.connector.service.asset.AssetService;
import com.smsc.headend.module.asset.dto.MeterDTO;
import com.smsc.headend.module.asset.entity.ComEntity;
import com.smsc.headend.module.asset.entity.Meter;
import com.smsc.headend.module.data.proto.DeviceStatusPoProto;
import com.smsc.headend.module.task.consts.TaskKafkaTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class DeviceStatusServiceImpl implements DeviceStatusService {
    @Autowired
    FeignAssetManagementService assetManagementService;
    @Autowired
    AssetService assetService;

    // default 60 minutes
    @Value("${device.refresh.online.interval:60}")
    Integer onlineRefreshInterval;

    // default 1440 minutes
    @Value("${device.plcMeterStatus.threshold.interval:1440}")
    Integer plcMeterStatusThreInterval;

    @Autowired
    KafkaTemplate kafkaTemplate;

    //设备上下线或者活动 发送消息至Asset-management ，更改业务状态
    @Override
    public void refreshDeviceStatus(ComEntity comEntity, Long meterId, ComEntity.CommunicationStatus communicationStatus) {
        DeviceStatusPoProto.DeviceStatusPo.Builder builder = DeviceStatusPoProto.DeviceStatusPo.newBuilder();
        builder.setStatus(communicationStatus.getCode())
                .setComDeviceId(comEntity.getDeviceId())
                .setComId(comEntity.getComId())
                .setTv(SystemClock.now())
                .setStatus(communicationStatus.getCode()).setMeterId(meterId == null ? 0 : meterId);
        DeviceStatusPoProto.DeviceStatusPo po = builder.build();
        kafkaTemplate.send(TaskKafkaTopic.DEVICE_STATUS_REFRESH, StrUtil.toString(comEntity.getComId()), po.toByteArray());
    }


    private boolean isComEntityOffline(ComEntity comEntity) {
        return (ObjectUtil.equals(ComEntity.CommunicationStatus.OFFLINE.getCode(), comEntity.getComStatus()) || ObjectUtil.equals(ComEntity.CommunicationStatus.NEVER.getCode(), comEntity.getComStatus()));
    }

    private void updateMeterStatus(Meter meter) {
        MeterDTO meterDTO = new MeterDTO();
        meterDTO.setMeterId(meter.getMeterId());
        boolean isNeedUpdate = false;
        if (meter.getInstallStatus() != null && meter.getInstallStatus() != Meter.MeterInstallStatus.Installed.getCode()) {
            // 更新安装状态
            meterDTO.setInstallStatus(Meter.MeterInstallStatus.Installed.getCode());
            isNeedUpdate = true;
            log.debug("update meter install status {}", meter.getMeterId());
        }
        if (meter.getRegisterStatus() != null && meter.getRegisterStatus() != Meter.MeterRegisterStatus.Registerd.getCode()) {
            // 更新注册状态
            meterDTO.setRegisterStatus(Meter.MeterRegisterStatus.Registerd.getCode());
            isNeedUpdate = true;
            log.debug("update meter register status {}", meter.getMeterId());
        }
        if (meter.getChannelType().equals("PLC") && meter.getMountStatus() != null && meter.getMountStatus() != Meter.MeterMountStatus.Mounted.getCode()) {
            // 更新注挂接状态
            meterDTO.setMountStatus(Meter.MeterMountStatus.Mounted.getCode());
            isNeedUpdate = true;
            log.debug("update meter mount status {}", meter.getMeterId());
        }
        if (isNeedUpdate) {
            assetManagementService.updateMeterStatus(meterDTO);
            assetService.clearMeterCacheById(meter.getMeterId());
        }
    }


}
